package com.x.gzcrm.service.impl;


import com.x.gzcrm.mapper.UserMapper;
import com.x.gzcrm.model.PageResult;
import com.x.gzcrm.model.User;
import com.x.gzcrm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUserName(username);
    }

    @Override
    public PageResult<User> findPageResult(User condition, int page, int pageSize) {
        PageResult<User> result= new  PageResult<User>();
        result.setCode(0);
        /**
         * 查询参数先设置为空
         */
        System.out.println("User:condition"+condition);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("condition",condition);//模糊查询条件
        params.put("start",(page-1) * pageSize);
        params.put("pageSize",pageSize);
        //获取总记录数据
        result.setCount(userMapper.findCountByMap(params));

        //获取查询的数据
        result.setData(userMapper.findListByMap(params));
        return result;
    }

    @Override
    public void save(User user, Integer[] roleIds) {

        StringBuffer sb=new StringBuffer();
        for (Integer ids : roleIds)
        {
            sb.append(ids);
            System.out.print(ids);
        }
        String strroleIds=sb.toString();
        if(user.getId() == 0){//插入新数据
            userMapper.insert(user);
        }
        else{//更新数据
            //1.更改t_user表[自己实现]
            userMapper.updateUser(user);
            //删除以前的用户的角色数据
            userMapper.deleteUserRole(user.getId());

//            //2.更改用户的角色数据(重新插入用户角色数据)
//            for (Integer roleId : roleIds){
//                userMapper.insertUserAndRole(user.getId(),roleId);
//            }
        }

        //批处理插入用户信息
        userMapper.insertUserAndRoleBatch(user.getId(), strroleIds);


    }

    @Override
    public User findUserAndRolesByUserId(Integer userId) {
        return userMapper.findUserAndRolesByUserId(userId);
    }
}
